<template>
  <div class="container">
    <el-dialog
      :before-close="handleClose"
      :title="status === 'Add' ? '新增靓号' : '编辑靓号'"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item
          :prop="status === 'Add' ? 'good_code' : undefined"
          label="靓号"
        >
          <el-input
            v-if="status === 'Add'"
            v-model.number="ruleForm.good_code"
            placeholder="请输入靓号"
            style="width: 40%;"
          >
          </el-input>
          <!-- 只展示 当为编辑时         -->
          <span v-else>{{ detail.product_name }}</span>
        </el-form-item>

        <el-form-item label="靓号类别" prop="cate1_id">
          <el-select
            v-model="ruleForm.cate1_id"
            placeholder="请选择靓号类别"
            @change="parentChange"
          >
            <el-option
              v-for="item in parentList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          :prop="liangChildList.length > 0 ? 'cate2_id' : 'cate2_id_none'"
          label="靓号二级分类"
        >
          <el-select
            v-model="ruleForm.cate2_id"
            placeholder="请选择靓号二级分类"
          >
            <el-option
              v-for="item in liangChildList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <div v-for="item in dayList" class="flex">
          <el-form-item label="天数">
            <el-input
              v-model="item.day"
              placeholder="请输入天数"
              style="width: 80%;"
            ></el-input>
          </el-form-item>

          <el-form-item label="价格">
            <el-input
              v-model="item.price"
              placeholder="请输入靓号价格"
              style="width: 90%;"
            ></el-input>
          </el-form-item>
        </div>

        <div style="margin-left: 120px;">
          <el-button
            plain
            size="small"
            type="primary"
            @click="addDayNumberClick"
          >+ 增加
          </el-button>
          <el-button plain size="small" type="danger" @click="delDay"
          >- 删除
          </el-button>
        </div>

        <div class="flex">
          <el-form-item label="">
            <el-radio
              v-model="permanentList[0].permanent"
              :label="9999"
              style="width: 80%"
            >永久
            </el-radio>
          </el-form-item>
          <el-form-item label="价格" style="margin-left: 15%">
            <el-input
              v-model="permanentList[0].price"
              placeholder="请输入永久靓号价格"
              style="width: 90%;"
            ></el-input>
          </el-form-item>
        </div>

        <el-form-item label="靓号状态" prop="sale_status">
          <el-radio-group v-model="ruleForm.sale_status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="2">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
        >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { addLiang, editLiang } from '../../../../../../api/personalizedMall/goodNumberPool'

export default {
  name: 'addEditModal',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    // 用于控制当前模态框所处于的状态  Add为新增模态框  Edit 为编辑模态框
    status: {
      type: String,
      default: 'Add'
    },
    detail: {
      type: Object,
      default: () => {
      }
    },
    parentList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      liangChildList: [],
      ruleForm: {
        good_code: undefined, // 靓号，必须
        cate1_id: undefined, // 一级分类id，必须
        cate2_id: undefined, // 二级分类id，必须
        sale_status: undefined, // 销售状态：1：上架；2：下架，必
        days_price: undefined
        // picture: undefined
      },
      permanentList: [
        {
          permanent: undefined,
          price: undefined
        }
      ],
      dayList: [{ day: undefined, price: undefined }],
      rules: {
        good_code: [
          { required: true, message: '请输入靓号', trigger: 'blur' },
          { type: 'number', message: '请输入数字' }
        ],
        cate1_id: [
          { required: true, message: '请选择靓号类别', trigger: 'blur' }
        ],
        sale_status: [
          { required: true, message: '请选择靓号状态', trigger: 'blur' }
        ],
        cate2_id: [
          { required: true, message: '请选择靓号二级分类', trigger: 'blur' }
        ],
        cate2_id_none: [
          { required: false, message: '请选择靓号二级分类', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleClose(done) {
      this.$emit('update:dialogVisible', false)
      this.resetRuleForm()
    },
    submitForm(formName) {
      // 处理数据
      let dayArr = []
      this.dayList.map(item =>
        item.day || item.price ? dayArr.push(item) : false
      )
      this.permanentList.map(item =>
        item.permanent === 9999 || item.price
          ? dayArr.push({
            day: 9999,
            price: item.price
          })
          : false
      )
      this.ruleForm.days_price = JSON.stringify(dayArr)

      this.$refs[formName].validate(async valid => {
        if (valid) {
          let detail = []
          if (this.status === 'Add') {
            detail = await addLiang({ ...this.ruleForm })
          } else {
            detail = await editLiang({ ...this.ruleForm })
          }
          if (detail.code === 200) {
            this.$message.success(status === 'Add' ? '新增成功' : '编辑成功')
            this.$emit('updateTable')
            this.$emit('update:dialogVisible', false)
            this.resetRuleForm()
          }
        } else {
          return false
        }
      })
    },
    resetRuleForm() {
      for (const argumentsKey in this.ruleForm) {
        this.ruleForm[argumentsKey] = undefined
      }
      this.permanentList = [
        {
          permanent: undefined,
          price: undefined
        }
      ]
      this.dayList = [{ day: undefined, price: undefined }]
      this.$emit('update:status', 'Add')
      this.resetForm('ruleForm')
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    /**
     * parentChange
     * @desc 当靓号类别的数据发生改变时, 改变二级列别的数据
     */
    parentChange(val) {
      this.ruleForm.cate2_id = undefined
      this.parentList.map(item =>
        item.id === val ? (this.liangChildList = item.sub_cates) : undefined
      )
    },

    handleSuccess() {
      this.ruleForm.picture = this.ossLastImgUrl
    },
    /**
     * addDayNumberClick
     * @desc 新增天数
     */
    addDayNumberClick() {
      this.dayList.push({ day: undefined, price: undefined })
    },
    delDay() {
      this.dayList.pop()
    }
  },
  watch: {
    status(newVal) {
      if (newVal === 'Edit') {
        if (this.detail.product_price.length !== 0) this.dayList = []
        this.detail.product_price.map(item => {
          item.day === 9999
            ? (this.permanentList = [{ permanent: 9999, price: item.price }])
            : this.dayList.push(item)
        })
        this.ruleForm.good_code = this.detail.product_name

        this.parentList.map(item => {
          if (item.title === this.detail.cate1_name) {
            this.ruleForm.cate1_id = item.id
            item.sub_cates.map(item1 => {
              if (item1.title === this.detail.cate2_name) {
                this.ruleForm.cate2_id = item1.id
              }
            })
          }
        })

        this.ruleForm.sale_status = this.detail.on_sale
        this.ruleForm = Object.assign(this.ruleForm, this.detail)
      }
    }
  }
}
</script>

<style scoped>
::v-deep.avatar-uploader .el-upload {
  border        : 1px dashed #d9d9d9;
  border-radius : 6px;
  cursor        : pointer;
  position      : relative;
  overflow      : hidden;
}

.avatar-uploader .el-upload:hover {
  border-color : #409eff;
}

.avatar-uploader-icon {
  font-size   : 28px;
  color       : #8c939d;
  width       : 100px;
  height      : 100px;
  line-height : 100px;
  text-align  : center;
}

.avatar {
  width   : 100px;
  height  : 100px;
  display : block;
}
</style>
